package com.zycfc.zsf.boot.mybatis.dynamicdatasource;

import javax.sql.*;
import java.util.*;
import org.apache.ibatis.session.*;
import org.mybatis.spring.*;
import com.zycfc.zsf.boot.mybatis.dynamicdatasource.interceptor.*;
import org.apache.ibatis.plugin.*;

public abstract class AbstractDataSourceConfiguration
{
    protected static final int TX_METHOD_TIMEOUT = 30000;
    
    public MyAbstractRoutingDataSource createRoundRobinDataSouceProxy(final DataSource writeDataSource, final List<DataSource> readDataSources) {
        final int size = readDataSources.size();
        final MyAbstractRoutingDataSource proxy = new MyAbstractRoutingDataSource(size, writeDataSource, readDataSources);
        final Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
        targetDataSources.put(DataSourceType.write.getType(), writeDataSource);
        int i = 0;
        for (final DataSource dataSource : readDataSources) {
            targetDataSources.put(DataSourceType.read.getType() + i, dataSource);
            ++i;
        }
        proxy.setDefaultTargetDataSource((Object)writeDataSource);
        proxy.setTargetDataSources((Map)targetDataSources);
        return proxy;
    }
    
    public SqlSessionFactory createSqlSessionFactory(final String aliasesPackage, final MyAbstractRoutingDataSource roundRobinDataSouceProxy) throws Exception {
        final SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setTypeAliasesPackage(aliasesPackage);
        bean.setDataSource((DataSource)roundRobinDataSouceProxy);
        final SqlSessionFactory sqlSessionFactory = bean.getObject();
        final DynamicDatasourceInterceptor interceptor = new DynamicDatasourceInterceptor();
        sqlSessionFactory.getConfiguration().addInterceptor((Interceptor)interceptor);
        return sqlSessionFactory;
    }
}
